package com.comm.update;

import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载管理器
 * Created by chenxunlin01 on 2017/10/10.
 */

public class AppDownloadManager extends AsyncTask<Void, Integer, Integer> {

    public final static int DOWNLOAD_COMPLETE = 1;// 完成
    public final static int DOWNLOAD_FAIL = -2;// 失败
    public final static int DOWNLOAD_SPACE_NOT_ENOUGH = -3;// 空间不够

    private DownloadApkInfo downloadApkInfo;
    private UpdateService.UpdateHandler handler;

    /**
     * 启动app下载
     *
     * @param downloadApkInfo
     */
    public void start(DownloadApkInfo downloadApkInfo, UpdateService.UpdateHandler handler) {
        this.downloadApkInfo = downloadApkInfo;
        this.handler = handler;
        execute();
    }

    @Override
    protected Integer doInBackground(Void... voids) {
        if (downloadApkInfo == null) {
            return DOWNLOAD_FAIL;
        }

        long downloadSize = 0;   //下载的大小
        long totalSize = 0;   //总大小
        int count = 0;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            HttpURLConnection conn = createConnection(downloadApkInfo.downloadUrl);
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                totalSize = conn.getContentLength();
                is = conn.getInputStream();
                File file = Utils.createFile(downloadApkInfo.appLocalPath);
                fos = new FileOutputStream(file);
                int len = 0;
                byte[] buffer = new byte[1024];
                //将输入流写入到我们定义好的文件中
                while ((len = is.read(buffer)) != -1) {
                    if (isCancelled()) {
                        throw new RuntimeException();
                    }
                    fos.write(buffer, 0, len);
                    downloadSize += len;
                    if ((count == 0) || (int) (downloadSize * 100 / totalSize) >= count) {
                        count += 5;
                        publishProgress((int) (downloadSize * 100 / totalSize));
                    }
                }
                //将缓冲刷入文件
                fos.flush();
                conn.disconnect();
                // md5校验
                String fileMd5 = SecurityUtil.getInstance().getMessageMd5(downloadApkInfo.appLocalPath);
                if (!downloadApkInfo.md5.equals(fileMd5)) {
                    return DOWNLOAD_FAIL;
                }

                return DOWNLOAD_COMPLETE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DOWNLOAD_FAIL;
        } finally {
            //在最后，将各种流关闭
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return DOWNLOAD_FAIL;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        if (isCancelled()) {
            integer = DOWNLOAD_FAIL;
        }

        Message msg = Message.obtain();
        msg.what = integer;
        msg.obj = downloadApkInfo.appLocalPath;
        handler.sendMessage(msg);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Log.e("aa", values[0] + "");
    }

    private HttpURLConnection createConnection(String downloadUrl) throws IOException {
        // 统一资源
        URL url = new URL(downloadUrl);
        // 连接类的父类，抽象类
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(1000);
        conn.setDoInput(true);
        return conn;
    }
}
